import Cookies from 'js-cookie'

export default {
  state: {
    currentMenu: null,
    isCollapse: false,
    tabList: [{ path: '/', label: '首页', icon: 'home', name: 'home' }],
    menus: [],
  },
  mutations: {
    // 登录成果后把后台返回来的权限菜单数据保存到vuex中的menus中，同时cookie中也保存一份
    setMenu(state, val) {
      state.menus = val
      Cookies.set('menu', JSON.stringify(val))
    },
    clearMenu(state) {
      state.menus = []
      Cookies.remove('menu')
    },
    addMenu(state, router) {
      var menu = Cookies.get('menu')
      if (!menu) return
      let menu2 = JSON.parse(menu)
      state.menus = menu2
      let currentMenu = [
        {
          path: '/',
          name: 'home',
          component: () => import('@/views/MyHome.vue'),
          children: [],
        },
      ]
      menu2.forEach((element) => {
        if (element.children) {
          element.children = element.children.map((item) => {
            item.component = () => import(`@/views/${item.url}`)
            return item
          })
          // 把遍历好的子路由展开放入第一级路由的子目录中，
          currentMenu[0].children.push(...element.children)
        } else {
          element.component = () => import(`@/views/${element.url}`)
          currentMenu[0].children.push(element)
        }
      })
      router.addRoute(currentMenu[0])
    },
    selectMenu(state, val) {
      // val.name === 'home' ? (state.currentMenu = null) : (state.currentMenu = val)
      if (val.name === 'home') {
        state.currentMenu = null
      } else {
        state.currentMenu = val
        let index = state.tabList.findIndex((item) => item.name === val.name)
        index === -1 ? state.tabList.push(val) : ''
      }
    },
    closeTab(state, val) {
      let index = state.tabList.findIndex((item) => item.name === val.name)
      state.tabList.splice(index, 1)
    },
    toogleCollapse(state) {
      state.isCollapse = !state.isCollapse
    },
  },
  actions: {},
}
